<?php

/**
 * cms actions.
 *
 * @package    DUYTAN
 * @subpackage gallery
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class categoryListAction extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeCategoryList(sfWebRequest $request)
  {
	$this->gallery_category_form = new AdminGalleryCategoryForm();
	if ($request->hasParameter('create') && $request->getParameter('create') == 'Create') {
		$res = $request->getParameter('gallery_category');
		$this->is_create_action = false;
		if ($res['name'] != '') {
			$gallery_category = new VTNSGalleryCategory();
            $gallery_category->gallery_category_id = $res['gallery_category_id'];
			$gallery_category->name = $res['name'];
			$gallery_category->position = $res['position'];
			$gallery_category->created_at = date(DATE_ISO8601);
			$gallery_category->updated_at = date(DATE_ISO8601);
			try {
				$gallery_category->save();
				$this->create_success = true;
			} catch (sfException $e) {
				echo $e->getMessage();
			}
		}
		
	} else {
		$this->allGalleryCategories = $this->showAllGalleryCategories();
		$q = Doctrine_Query::create()
			->from('VTNSGalleryCategory c');
        $res = $request->getParameter('gallery_category');
		$this->sort_by = $request->getParameter('sort_by', 'created_at');
    	if ($request->getParameter('sort_order', 1))
        	$this->sort_order = 'desc';
    	else
        	$this->sort_order = 'asc';
    	if (Doctrine_Core::getTable('VTNSGalleryCategory')->hasField($this->sort_by))
        	$q->orderBy('c.'.$this->sort_by.' '.strtoupper($this->sort_order));
		$this->pager = new sfDoctrinePager('VTNSGalleryCategory', 10000);
		$this->pager->setQuery($q);
    	$this->pager->setPage($request->getParameter('page', 1));
    	$this->pager->init();
		if ($request->isXmlHttpRequest()) {
        	return 'Ajax';
    	} else return SfView::SUCCESS;
	}
  }
  
  private function showAllGalleryCategories()
  {
	$str = "";
	$c = Doctrine_Query::create()
		->select('c.*')
		->from('VTNSGalleryCategory c')
		->orderBy('c.position');
	$results = $c->fetchArray();
	$spaces = "";
	foreach ($results as $result)
	{
		$str .="<tr>
			<td>".$result['id']."</td>
			<td>".$spaces."<a href=".($this->getController()->genUrl("@gallery_list?gallery_category_id=".$result['gallery_category_id']))."</a></td>
			<td style=text-align:center> ".$result['position']."</td>
			<td style=text-align:center>".$result['created_at']."</td>
			<td style=text-align:center><a href=".($this->getController()->genUrl("@gallery_category_edit?gallery_category_id=".$result['gallery_category_id'])).">Sửa</a></td>
		</tr>";
	}
    return $str;
  }
}